import React, { useContext } from "react";
import PubSub from "pubsub-js"
import UploadContainer from "../../../UploadContainer";

import fileNodeApi from "../../../../api/fileNode";
import fileTool from "../../../../utils/file-tool";
import uuid from "../../../../utils/uuid";

import Context from "../../context"

import fileSVG from "../../../../assets/img/file.svg";
import dirSVG from "../../../../assets/file-icon/dir.svg";
import './index.scss'
import asyncPool from "../../../../utils/asyncPool";




export default function List() {

    const { root } = useContext(Context)

    function upload(parentId, file, hash) {
        return async function() {
            let chunkList = fileTool.chunk(file)
            let md5 = await fileTool.md5(chunkList)
            PubSub.publish('EV_TASK_UPDATE', {
                hash,
                data: {
                    status: 'uploading'
                }
            })
            let { data: { taskId } } = await fileNodeApi.createUpload({
                name: file.name,
                md5: md5,
                size: file.size,
                lastModified: file.lastModified,
                chunkCount: chunkList.length,
                parentId: parentId
            })

            let waitUploadChunkCount = chunkList.length
            let index = 0;

            while (index < waitUploadChunkCount) {
                let formData = new FormData();
                formData.append('file', chunkList[index].file)
                formData.append('seq', chunkList[index].seq)
                formData.append('taskId', taskId)
                try {
                    let { data: { process } } = await fileNodeApi.uploadChunk(formData)
                    PubSub.publish('EV_TASK_UPDATE', {
                        hash,
                        data: {
                            process: (process * 100).toFixed(2) + "%"
                        }
                    })
                    index++
                } catch (e) {
                    console.log('网络繁忙')
                }
            }

            PubSub.publish('EV_TASK_UPDATE', {
                hash,
                data: {
                    status: 'finished'
                }
            })
            PubSub.publish('EV_FLASH_FILE_NODE')
        }
    }

    async function uploadFiles(files) {
        for (let i = 0;i < files.length;i++) {
            let file = files[i]
            let hash = uuid()
            PubSub.publish('EV_TASK_ADD', {
                fileName: file.name,
                size: file.size,
                hash: hash,
                uploadPath: root.name,
                process: '0%',
                status: 'wait'
            })
            asyncPool.execute(upload(root.id, file, hash)).then(() => {})
        }
    }

    async function uploadFolder(files) {
        let nodeList = []
        for (let i = 0; i < files.length;i++) {
            nodeList.push({
                name: files[i].name,
                path: files[i].webkitRelativePath,
                size: files[i].size,
                isDir: false,
                type: files[i].type,
                lastModified: files[i].lastModified
            })
        }

        const resp = await fileNodeApi.newFileTree(root.id, nodeList)

        PubSub.publish('EV_FLASH_FILE_NODE')

        for (let i = 0;i < files.length;i++) {
            let file = files[i]
            let hash = uuid()
            PubSub.publish('EV_TASK_ADD', {
                fileName: file.name,
                size: file.size,
                hash: hash,
                uploadPath: root.name,
                process: '0%',
                status: false
            })

            asyncPool.execute(upload(resp.data[file.webkitRelativePath], file, hash)).then(() => {})
        }
    }

    return (
        <div  className='list'>
            <UploadContainer className='item' multiple={ true } upload={ uploadFiles }>
                <img src={ fileSVG } alt={ 'file' }/>
                <span>上传文件</span>
            </UploadContainer>
            <UploadContainer className='item' multiple={ true } directory={ true } upload={ uploadFolder } >
                <img src={ dirSVG } alt={ 'dir' } />
                <span>上传文件夹</span>
            </UploadContainer>
        </div>
    )
}